#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/11/2 18:15
# @Author : 闫峰
# @File    : api.py
import json
from retrying import retry
from common.setting import ensure_path_sep
import requests
from utils.mysqlUtils.db_pool import Database
session = requests.session()
import hashlib
import time


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def url_parse(value):
    """
    编码
    :param value:   要编码的字符串
    :return:
    """
    import urllib
    from urllib import parse
    # URL编码
    new_txt = urllib.parse.quote(value)
    return new_txt


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def md5_encryption(value):
    """ md5 加密"""
    str_md5 = hashlib.md5(str(value).encode(encoding='utf-8')).hexdigest()
    return str_md5


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def set_time():
    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # localtime = time.strftime("yyyy-MM-dd HH:mm:ss ZZZ", time.localtime())
    return localtime + " +0800"
    # return localtime


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def get_accessToken(appKey, appSecret):
    json = {
        "grantType": "client_credentials",
        "appKey": appKey,
        "appSecret": appSecret
    }
    url = "https://api.joybuy.com/token"
    res = session.get(url=url, params=json)
    return res.json().get("accessToken")


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def get_sign(appKey, accessToken, method, format, version, timestamp, param, appSecret):
    list1 = ["appKey", "accessToken", "method", "format", "version", "timestamp", "param"]
    list1.sort()
    # print(list1)
    str1 = list1[0] + accessToken + list1[1] + appKey + list1[2] + format + list1[3] + method + list1[4] + param + \
           list1[5] + timestamp + list1[6] + version
    # print(str1)
    str2 = appSecret + str1 + appSecret
    return md5_encryption(str2)


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def get_timestamp():
    timestamp = set_time()
    timestamp = url_parse(timestamp)
    return timestamp


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def get_result(appKey, appSecret, method, param):
    timestamp = set_time()
    format = "json"
    version = "V1"
    accessToken = get_accessToken(appKey, appSecret)
    sign = get_sign(appKey, accessToken, method, format, version, timestamp, param, appSecret)
    # print(sign)
    timestamp = url_parse(timestamp)
    param = url_parse(param)
    url = f"https://api.joybuy.com/router?appKey={appKey}&accessToken={accessToken}&method={method}&format=json&version=V1&timestamp={timestamp}&sign={sign}&param={param}"
    res = session.get(url)
    # return  json.dumps(res.json(),ensure_ascii=False)
    # return res.json()
    res = res.text
    res = json.loads(res)
    res = json.dumps(res, indent=4)
    # res = res.json()
    # print(type(res))
    # res  = json.loads(res)
    # res = json.dumps(res,indent=4)
    return res


@retry(stop_max_attempt_number=300, wait_fixed=1000)
def get_result_bei(ordersourceid,method, param):
    timestamp = set_time()
    db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "HWY-ZH-GZ-RDS-JavaCommon")
    sql1 = """SELECT dev_idseller_id,cert_idaccess_key_id,user_token_secret_access_key 
    FROM `zhcxkj-center-data`.rb_order_source_ebay_amazon_api WHERE order_source_id=%s;"""
    res1 = db.fetch_all(sql1, (ordersourceid,))
    appKey = res1[0]['dev_idseller_id']
    appSecret = res1[0]['cert_idaccess_key_id']
    accessToken = res1[0]['user_token_secret_access_key']
    format = "json"
    version = "V1"
    sign = get_sign(appKey, accessToken, method, format, version, timestamp, param, appSecret)
    timestamp = url_parse(timestamp)
    param = url_parse(param)
    url = f"https://api.joybuy.com/router?appKey={appKey}&accessToken={accessToken}&method={method}&format=json&version=V1&timestamp={timestamp}&sign={sign}&param={param}"
    try:
        res = session.post(url)
    except Exception as e:
        raise e
    if res.status_code == 200:
        # return res.json(encodings='utf-8')


        return  json.dumps(res.json(),indent=4).encode('utf-8').decode('unicode_escape')
    else:
        raise Exception("status_code!=200")
    # res = session.post(url=url,data=data)
    # return  json.dumps(res.json(),ensure_ascii=False)
    # return res.json()
    # res = res.text
    # res = json.loads(res)
    # res = json.dumps(res, indent=4)
    # res = res.json()
    # print(type(res))
    # res  = json.loads(res)
    # res = json.dumps(res,indent=4)
    # return res.encode('utf-8').decode('unicode_escape')
    # print(json.dumps(res.json(),indent=4))
if __name__ == '__main__':
    str_a = """c7e0a1a63542be4de3cb5488f9fba8149e8fc290access_token2nifvmpyymvypwmcms5ct4uqqudrwgpmzb
    cnmkt1jzjkuaf3x56iixymapp_keyf9d5cc9313893a20d5aa85c654e8f503data_typeJSONsendRequestList[{"
    orderSendInfoList":[{"quantity":1,"orderSn":"211-21905473070712792","parentOrderSn":"PO-211-
    21905452099192792","goodsId":601099548666279,"skuId":17592352673534}],"carrierId":"699272611","t
    rackingNumber":"270324232756"}]sendType0timestamp1711009072typebg.logistics.shipment.confirmc7
    e0a1a63542be4de3cb5488f9fba8149e8fc290"""
    print(md5_encryption(str_a))